package cn.stimd.spring.validation;

import java.util.*;

/**
 * 持有一个错误集合，访问属性的具体功能交由子类完成
 * <p>
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public abstract class AbstractBindingResult implements BindingResult {
    private final String objectName;
    private final List<ObjectError> errors = new LinkedList<>();

    public AbstractBindingResult(String objectName) {
        this.objectName = objectName;
    }

    @Override
    public Map<String, Object> getModel() {
        Map<String, Object> model = new LinkedHashMap<>(2);
        model.put(getObjectName(), getTarget());                //目标对象
        model.put(MODEL_KEY_PREFIX + getObjectName(), this);    //错误实例
        return model;
    }

    @Override
    public void addError(ObjectError error) {
        this.errors.add(error);
    }


    @Override
    public String getObjectName() {
        return objectName;
    }

    @Override
    public FieldError getFieldError(String field) {
        for (ObjectError objectError : this.errors) {
            if (objectError instanceof FieldError) {
                FieldError fieldError = (FieldError) objectError;
                if (field.equals(fieldError.getField())) {
                    return fieldError;
                }
            }
        }
        return null;
    }

    @Override
    public FieldError getFieldError() {
        return (FieldError) this.errors.stream().filter(x -> x instanceof FieldError).findFirst().orElse(null);
    }


    @Override
    public List<FieldError> getFieldErrors() {
        List<FieldError> result = new LinkedList<>();
        for (ObjectError objectError : this.errors) {
            if (objectError instanceof FieldError) {
                result.add((FieldError) objectError);
            }
        }
        return Collections.unmodifiableList(result);
    }


    @Override
    public boolean hasErrors() {
        return !this.errors.isEmpty();
    }
}
